;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.GiftManage", [])
        .controller("GiftManageCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams) {
            $scope.activeFlag = [true, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };

            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.tabFlag = {};
            $scope.today = new Date();
            var tabFlag = {
                0: "详情",
                1: "新增",
                2: "编辑"
            };

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/giftticket/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/giftticket/exportAll")
            };
            $scope.orderObj = {};
            $scope.tableConfig = {
                fixedWidth: 150,
                scrollWidth: 1100,
                tableCol: [{
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        // clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "车号",
                        dataField: "vinCode",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "机型",
                        dataField: "machineType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "身份证号",
                        dataField: "idCardNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "手机号",
                        dataField: "phoneNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "赠送额度",
                        dataField: "giftAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已用额度",
                        dataField: "usedAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "剩余额度",
                        dataField: "residueAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "有效期",
                        dataField: "validityDate",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createTime",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "代金券名称",
                        dataField: "ticketName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "兑换码",
                        dataField: "ticketCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 110,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            var btnPermissionCode = {
                giftManageAdd: window.ActionCode.giftManageAdd,
                giftManageEdit: window.ActionCode.giftManageEdit,
                giftManageDel: window.ActionCode.giftManageDel,
                giftManageExport: window.ActionCode.giftManageExport,
            };

            $scope.btnPermission = {
                giftManageAdd: true,
                giftManageEdit: true,
                giftManageDel: true,
                giftManageExport: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            // $scope.checkDate = function (obj, startFiled, endFiled) {
            //     var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
            //     if (!!timeFormatObj.tStart) {
            //         obj[startFiled] = timeFormatObj.tStart;
            //     }
            //     if (!!timeFormatObj.tEnd) {
            //         obj[endFiled] = timeFormatObj.tEnd;
            //     }
            // };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };


            function initData() {
                $scope.tabFlag = {};
                $scope.orderObj = {};
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/giftticket/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.validityDate = $filter("YbDate")(item.validityDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createTime = $filter("YbDate")(item.createTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };


            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.batchDel = function () {
                var deleteList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        deleteList.push(item.id);
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除数据', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/giftticket/delete";
                    ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/giftticket/delete";
                    ybHttp.Post(service, reqUrl, {
                        id: id
                    }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(1);
            };


            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/giftticket/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = "编辑";
                    $scope.orderObj = data;
                    if (data.validityDate) {
                        data.validityDate = $filter("YbDate")(data.validityDate);
                    }
                    $scope.changeTab(2);
                });
            };

            $scope.saveData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/giftticket/create";
                if ($scope.tabFlag.type === 2) {
                    reqUrl = "/giftticket/update";
                }
                var param = angular.copy($scope.orderObj);
                if ($scope.orderObj.giftAmount < $scope.orderObj.usedAmount) {
                    ybWidget.ShowToaster('warning', '赠送额度不可小于已用额度，请设置合理的额度！');
                    $scope.orderObj.giftAmount = 0;
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };


            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            /* 设置金额 */
            $scope.setPrice = function () {
                if (!$scope.orderObj.giftAmount) {
                    $scope.orderObj.giftAmount = 0;
                }
                if (!$scope.orderObj.usedAmount) {
                    $scope.orderObj.usedAmount = 0;
                }
                $scope.orderObj.residueAmount = (parseFloat($scope.orderObj.giftAmount) - parseFloat($scope.orderObj.usedAmount)).toFixed(2);
            };

            $scope.onPriceChange = function () {
                if ($scope.orderObj.giftAmount < $scope.orderObj.usedAmount) {
                    ybWidget.ShowToaster('warning', '赠送额度不可小于已用额度，请设置合理的额度！');
                    $scope.orderObj.giftAmount = 0;
                }
            };


            $scope.import = function () {
                var param = {
                    name: "导入客户赠送款",
                    templateReqService: "device",
                    templateReqUrl: "/giftticket/customerImportTemplete",
                    importReqService: "device",
                    importReqUrl: "/giftticket/customer/import",
                    importErrorUrl: "",
                    templateType: "giftList"
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            (function () {
                getDataList();
                // $scope.timeString = $filter('date')($scope.today, 'yyyyMMdd');
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
